package com.gxuwz.attend.service;

import com.gxuwz.attend.dao.UserDao;
import com.gxuwz.attend.entity.User;
import com.gxuwz.attend.jdbc.DbManager;

import java.sql.Connection;
import java.util.List;

/**
 * 用户管理Service类
 * @author amu_1115@126.com
 */
public class UserService {
    //属性-引用哪些bean组件
    private UserDao userDao;
    private DbManager dbManager;

    /**
     * 验证用户名+密码的合法性
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public boolean checkUser(String username,String password)throws Exception{
         Connection conn =null;
         User user =new User();
         user.setUserid(username);
         user.setPassword(password);
         conn = dbManager.getConn();
         List<User> list =userDao.query(user,conn);
         return  !list.isEmpty();
    }

    /**
     * 查找所有用户记录
     * @param example
     * @return
     * @throws Exception
     */
    public List<User> list(User example)throws Exception{
        Connection conn =null;
        conn =dbManager.getConn();
        return userDao.query(example,conn);
    }
    /**
     * 添加用户信息
     * @param user
     */
    public void addUser(User user)throws Exception{
        //考虑从Service层实现多表SQL命令的执行的事务管理，所以引入dbManager获取一个Connection对象并开启手动事务处理
        Connection conn =null;
        try{
             conn =dbManager.getConn();
             //开启手动事务管理
             conn.setAutoCommit(false);
             userDao.insert(user,conn);
             //提交事务
             conn.commit();
        }catch (Exception e){
             e.printStackTrace();
             //事务回滚
             conn.rollback();
             throw e;
        }finally {
            //关闭连接
             dbManager.close(conn);
        }
    }
    public void deleteUser(String id)throws Exception{
        //考虑从Service层实现多表SQL命令的执行的事务管理，所以引入dbManager获取一个Connection对象并开启手动事务处理
        Connection conn =null;
        try{
            conn =dbManager.getConn();
            //开启手动事务管理
            conn.setAutoCommit(false);
            userDao.delete(id,conn);
            //提交事务
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            //事务回滚
            conn.rollback();
            throw e;
        }finally {
            //关闭连接
            dbManager.close(conn);
        }
    }
    //setter注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setDbManager(DbManager dbManager) {
        this.dbManager = dbManager;
    }
}
